<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>兑换码</h3>
    </div>
    <el-form :model="searchForm" ref="searchFormRef" label-width="auto">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="活动名称：" prop="queryCondition">
            <el-input placeholder="请输入活动名称" v-model="searchForm.queryCondition" clearable @blur="getData"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="兑换类型：" prop="type">
            <el-select v-model="searchForm.type" placeholder="请选择兑换类型" clearable @change="getData">
              <el-option v-for="item in cardtype" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="databox">
            <label class="el-form-item__label" style="margin-left: 1.5rem">活动时间：</label>
            <el-date-picker label="活动时间：" v-model="datavalue1" type="datetimerange" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
              @change="openActiveTime" />
          </div>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <!-- <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="resetForm(searchFormRef)" v-ripple>重置</el-button>
        <el-button v-ripple>刷新</el-button> -->
        <el-button @click="showDialog('add')" v-ripple>新增兑换码</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="ID" prop="id" width="55" align="center" />
        <el-table-column label="活动名称" prop="name" align="center" />
        <el-table-column label="兑换内容" prop="exchangeContent" align="center" />
        <el-table-column label="兑换类型" prop="type" align="center">
          <template #default="scope">
            <!-- :type="scope.row.type === 1 ? '' : 'info'" -->
            <el-button round size="small" :class="scope.row.type === 1 ? 'yqColor' : 'tyColor'">
              {{ scope.row.type === 1 ? '一券一码' : '通用码' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="活动时间：" prop="date" align="center">
          <template #default="scope">
            <div class="tag-group"><el-tag class="grouptag" type="success">起</el-tag>{{
              formatDate(scope.row.activityStartTime) }}
            </div>
            <div class="tag-group"><el-tag class="grouptag" type="info">止</el-tag>{{
              formatDate(scope.row.activityEndTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="已兑换/总数量" prop="weight" align="center">
          <template #default="scope">
            <el-link target="_blank" underline="never" type="primary" @click="linkmemberdetails(scope.row)">
              {{ scope.row.usedAmount }}/{{ scope.row.issueAmount }}</el-link>
          </template>
        </el-table-column>
        <el-table-column #default="scope" label="状态" align="center" prop="state">
          <el-switch v-model="scope.row.state" :inactive-value="0" :active-value="1"
            @click="editStatus(scope.row.id, scope.row.state)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="date" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <!-- 
        <el-table-column fixed="right" label="操作" width="100px" align="center">
          <template #default="scope">
            <el-row>
              <button-more :list="[
                { key: 'edit', label: '编辑' },
                { key: 'delete', label: '删除' }
              ]" @click="buttonMoreClick($event, scope.row)" />
            </el-row>
          </template>
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" align="center">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" content="兑换详情" placement="top-start">
              <button-table type="record" @click="linkmemberdetails(scope.row)" />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
              <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
              <button-table type="delete" @click="deleteRole(scope.row.id)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增兑换码' : '编辑兑换码'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <!-- 创建日期筛选 -->
          <div class="databox">
            <el-date-picker label="操作时间：" v-model="activeTime" type="datetimerange" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
              @change="changeActiveTime" />
          </div>
          <!-- end创建日期筛选 -->
        </el-form-item>
        <!-- <el-radio v-model="radio" label="1" :disabled="dialogType === 'edit' && radio === '2'">一券一码</el-radio>
          <el-radio v-model="radio" label="2" :disabled="dialogType === 'edit' && radio === '1'">通用码</el-radio> -->
        <el-form-item label="发放方式" prop="type">
          <el-radio-group v-model="radio" :disabled="dialogType === 'edit'">
            <el-radio v-for="item in cardtype" :key="item.value" :value="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放数量" prop="issueAmount" v-if="radio === '1'">
          <el-input v-model="form.issueAmount">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="可兑换数量" prop="issueAmount" v-if="radio === '2'">
          <el-input v-model="form.issueAmount">
            <template #append>张</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="clubCardId" label="会员权益">
          <el-select placeholder="请选择" multiple v-model="form.clubCardId">
            <el-option v-for="item in vipList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="state">
          <el-switch v-model="form.state" :inactive-value="0" :active-value="1" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useMenuStore } from '@/store/modules/menu'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { formatMenuTitle } from '@/router/utils/utils'
import { useRouter } from 'vue-router'
import { codeList, AddCodeList, vipType, EditCodeList, DelCodeList, EditState } from '@/api/userStudentsApi'
import { start } from 'repl'
import { get } from 'lodash'

const router = useRouter() // 使用useRouter获取路由实例
const loading = ref(false)

const dialogVisible = ref(false)

const radio = ref('1')
const cardtype = [
  {
    value: '1',
    label: '一券一码'
  },
  {
    value: '2',
    label: '通用码'
  }
]

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
})

const form = reactive({
  id: '',
  name: '',
  state: '1',
  issueAmount: '',
  ffNum: '',
  dhNum: '',
  startTime: '',
  endTime: '',
  clubCardId: []
})

const tableData = ref([
  // {
  //   id: '1',
  //   typename: 'aaa1111',
  //   weight: '1/100',
  //   date: '2021-01-08 12:30:45',
  //   status: true,
  //   showWorkTab: true,
  //   exchange_type: '一券一码',
  //   exchange_cont: '兑换内容兑换内容兑换内容兑换内容兑换内容'
  // },
  // {
  //   id: '1',
  //   typename: 'ddd1111',
  //   weight: '20/100',
  //   date: '2021-01-09 12:30:45',
  //   status: false,
  //   exchange_type: '通用码',
  //   exchange_cont: '兑换内容兑换内容兑换内容兑换内容兑换内容'
  // },
  // {
  //   id: '3',
  //   typename: 'ccc1111',
  //   weight: '30/100',
  //   date: '2021-01-10 12:30:45',
  //   status: true,
  //   exchange_type: '一券一码',
  //   exchange_cont: '兑换内容兑换内容兑换内容兑换内容兑换内容'
  // },
  // {
  //   id: '4',
  //   typename: 'bbb1111',
  //   weight: '50/100',
  //   date: '2021-01-11 12:30:45',
  //   status: false,
  //   exchange_type: '通用码',
  //   exchange_cont: '兑换内容兑换内容兑换内容兑换内容兑换内容'
  // }
])

const dialogType = ref('add')
const activeTime = ref<any>([])
const editNum = ref('')
const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type
  getVipData()
  if (type === 'edit' && row) {
    form.id = row.id
    form.name = row.name
    form.issueAmount = row.issueAmount
    form.startTime = row.activityStartTime
    form.endTime = row.activityEndTime
    form.clubCardId = row.clubCardId ? row.clubCardId.split(',') : []
    form.state = row.state
    editNum.value = row.issueAmount
    activeTime.value = [new Date(row.activityStartTime), new Date(row.activityEndTime)]
    radio.value = String(row.type)
  } else {
    form.id = ''
    form.name = ''
    form.issueAmount = ''
    form.startTime = ''
    form.endTime = ''
    form.clubCardId = []
    form.state = '1'
    activeTime.value = []
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
}

const defaultProps = {
  children: 'children',
  label: (data: any) => formatMenuTitle(data.meta?.title) || ''
}

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确定删除该兑换活动吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelCodeList(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }

  })
}
const changeActiveTime = (e: any) => {
  form.startTime = e[0]
  form.endTime = e[1]
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  loading.value = true
  await formEl.validate(async (valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      if (dialogType.value === 'add') {
        const res = await AddCodeList({
          name: form.name,
          activityStartTime: form.startTime ? formatDate(form.startTime) : '',
          activityEndTime: form.endTime ? formatDate(form.endTime) : '',
          type: Number(radio.value),
          issueAmount: form.issueAmount,
          clubCardId: form.clubCardId.length ? form.clubCardId.join(',') : ''
        })
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      } else {
        if (form.issueAmount < editNum.value) {
          ElMessage.error(`发放数量不能小于${editNum.value}张`)
        } else {
          const res = await EditCodeList({
            id: form.id,
            name: form.name,
            activityStartTime: form.startTime ? formatDate(form.startTime) : '',
            activityEndTime: form.endTime ? formatDate(form.endTime) : '',
            type: Number(radio.value),
            issueAmount: form.issueAmount,
            clubCardId: form.clubCardId.length ? form.clubCardId.join(',') : ''
          })
          if (res.code === '00000') {
            ElMessage.success(message)
            dialogVisible.value = false
            getData()
          }
        }

      }
    }
    loading.value = false
  })
}
const editStatus = async (id: number, state: number) => {
  const res = await EditState({
    id, state
  })
  if (res.code === '00000') {
    ElMessage.success('修改成功')
  }
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
const search = () => { getData() }
const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])
const openActiveTime = (e: any) => {
  if (e) {
    searchForm.queryStartTime = formatDate(e[0])
    searchForm.queryEndTime = formatDate(e[1])
  } else {
    searchForm.queryStartTime = ''
    searchForm.queryEndTime = ''
  }
  getData()
}
const datavalue1 = ref('') //创建时间：
const searchForm = reactive({
  queryCondition: '',
  type: '',
  queryStartTime: '',
  queryEndTime: ''
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  searchForm.queryStartTime = ''
  searchForm.queryEndTime = ''
  datavalue1.value = ''
}
const searchFormRef = ref<FormInstance>()
const changeColumn = (list: any) => {
  columns.values = list
}

interface MemberItem {
  type: number
  id: string
  name: string
  exchangeContent: string
  cdkey: string
  issueAmount: string
  usedAmount: string
}
const linkmemberdetails = function (item: MemberItem) {
  setTimeout(() => {
    router.push({
      name: 'memberPublish_details',
      query: {
        type: item.type,
        id: item.id,
        name: item.name,
        exchangeContent: item.exchangeContent,
        cdkey: item.cdkey,
        issueAmount: item.issueAmount,
        usedAmount: item.usedAmount
      }
    })
  }, 0)
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}
async function getData() {
  try {
    tableLoading.value = true
    const params = filterEmptyValues(searchForm)
    const { code, data } = await codeList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...params
    })
    if (code === '00000' && data) {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}
interface vipItem {
  value: string
  label: string
}
const vipList = ref<vipItem[]>([])
const getVipData = async () => {
  const res = await vipType()
  vipList.value = res.data
}
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.tag-group {
  margin-top: 0.5rem;
}

.grouptag {
  margin-right: 0.5rem;
}

.tyColor {
  color: #409eff;
  border: 1px solid #409eff;
}
</style>
